package io.aicn.lowcode.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.aicn.lowcode.dto.UserCreate;
import io.aicn.lowcode.dto.UserUpdate;
import io.aicn.lowcode.entity.User;
import io.aicn.lowcode.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserService extends ServiceImpl<UserMapper, User> implements IUserService {
    
    public List<User> searchUsers(String name, String email, Integer minAge, Integer maxAge) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(name)) {
            queryWrapper.like(User::getName, name);
        }
        if (StringUtils.hasText(email)) {
            queryWrapper.like(User::getEmail, email);
        }
        if (minAge != null) {
            queryWrapper.ge(User::getAge, minAge);
        }
        if (maxAge != null) {
            queryWrapper.le(User::getAge, maxAge);
        }
        
        return baseMapper.selectList(queryWrapper);
    }
    
    public User createUser(UserCreate userCreate) {
        User user = new User();
        user.setName(userCreate.getName());
        user.setAge(userCreate.getAge());
        user.setEmail(userCreate.getEmail());
        
        // Generate ID (in real application, this would be auto-generated by database)
        user.setId(System.currentTimeMillis());
        
        baseMapper.insert(user);
        return user;
    }
    
    public User updateUser(Long id, UserUpdate userUpdate) {
        User user = baseMapper.selectById(id);
        if (user == null) {
            return null;
        }
        
        if (userUpdate.getName() != null) {
            user.setName(userUpdate.getName());
        }
        if (userUpdate.getAge() != null) {
            user.setAge(userUpdate.getAge());
        }
        if (userUpdate.getEmail() != null) {
            user.setEmail(userUpdate.getEmail());
        }
        
        baseMapper.updateById(user);
        return user;
    }
    
    public boolean deleteUser(Long id) {
        return baseMapper.deleteById(id) > 0;
    }
    
    public List<User> getAllUsers() {
        return baseMapper.selectList(null);
    }
    
    public User getById(Long id) {
        return baseMapper.selectById(id);
    }
}